package com.sxz.sbs.http.retrofit;

import android.content.Context;

import com.sxz.sbs.BuildConfig;
import com.sxz.sbs.app.App;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.http.request.CarPlaceConverterFactory;
import com.sxz.sbs.http.request.NullConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Retrofit 辅助类
 */
public class RetrofitHelper {

    // private static HashSet<String> cookies   = new HashSet<>();
    public static <T> T initRetrofit(OkHttpClient okHttpClient, Class<T> serverApi) {
        return new Retrofit
                .Builder()
                .baseUrl(AppConstant.BASE_URL)
                .addConverterFactory(new NullConverterFactory())
                .addConverterFactory(CarPlaceConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
                .create(serverApi);
    }

    public static OkHttpClient getOkHttpClient(Context context) {
        Cache cache = new Cache(context.getCacheDir(), 50 * 1024 * 1024);
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        //添加拦截
        if (BuildConfig.DEBUG) {
            okHttpClient.addInterceptor(new LoggingInterceptor());
        }
        okHttpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                    Request original = chain.request();
                    Request.Builder requestBuilder = original.newBuilder()
                            //token
                            .header("Authorization", App.preferences.getValue(AppConstant.Preference.TOKEN)==null?"":App.preferences.getValue(AppConstant.Preference.TOKEN));
                    Request request = requestBuilder.build();
                    return chain.proceed(request);
            }
        });
        return okHttpClient
                .retryOnConnectionFailure(true)
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .cache(cache)
                .build();
    }
    public static <T> T uploadAPK(OkHttpClient okHttpClient, Class<T> serverApi,String url) {
        return new Retrofit
                .Builder()
                .baseUrl(url)
                .addConverterFactory(new NullConverterFactory())
                .addConverterFactory(CarPlaceConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build()
                .create(serverApi);
    }


}
